﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using crmservice;
using crmdiscoveryservice;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

/// <summary>
/// Creates a CrmService object
/// </summary>
public class CRMServiceFactory
{
    public static CrmService CreateCRMService(string orgName)
    {
        //Load Organization
        BypassCertificateError();
        CrmDiscoveryService discovery = new CrmDiscoveryService();
        discovery.UseDefaultCredentials = true;
        RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
        RetrieveOrganizationsResponse orgResp = (RetrieveOrganizationsResponse)discovery.Execute(orgRequest);
        OrganizationDetail orgDetail = null;

        foreach (OrganizationDetail orgInfo in orgResp.OrganizationDetails)
        {
            if (orgInfo.OrganizationName.Equals(orgName))
            {
                orgDetail = orgInfo;
                break;
            }
        }
        if (orgDetail == null)
            throw new Exception("Organization name not found");

        //Load Service
        CrmAuthenticationToken token = new CrmAuthenticationToken();
        token.AuthenticationType = Microsoft.Crm.Sdk.AuthenticationType.AD;
        token.OrganizationName = orgDetail.OrganizationName;

        // define the service
        CrmService crmService = new CrmService();
        crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
        crmService.CrmAuthenticationTokenValue = token;
        return crmService;
    }


    /// <summary>         
    /// solution for exception         
    /// System.Net.WebException:          
    /// The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.        
    /// </summary>         
    public static void BypassCertificateError()
    {
        ServicePointManager.ServerCertificateValidationCallback +=
            delegate(
            Object sender1,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };
    }
}
